<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="stationId">
        <el-select v-model="queryParams.chargeStationId" clearable placeholder="请选择场站">
          <el-option
            v-for="dict in stationListAll"
            :key="dict.id"
            :label="dict.stationName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="platformAgentId">
        <!--        <el-input
                  v-model="queryParams.platformAgentId"
                  placeholder="请输入代理商ID"
                  clearable
                  @keyup.enter.native="handleQuery"
                />-->
        <el-form-item label="" prop="platformAgentId">
          <!--        <el-input
                    v-model="queryParams.platformAgentId"
                    placeholder="请输入代理商ID"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />-->
          <el-select
            v-model="queryParams.platformAgentId"
            placeholder="代理商名称"
            clearable
            size="small">
            <el-option
              v-for="area in agentList"
              :key="area.id"
              :label="area.agentName"
              :value="area.id"
            />
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="" prop="shareInfoId">
        <el-input
          v-model="queryParams.shareInfoId"
          placeholder="请输入分润规则ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入待分账总金额分"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="payAmount">
        <el-input
          v-model="queryParams.payAmount"
          placeholder="请输入已分账总金额分"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="timeExport">
        <el-date-picker
          v-model="queryParams.timeExport"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          clearable
          end-placeholder="结束日期"
          range-separator="至"
          start-placeholder="开始日期"
          style="width: 250px"
          type="daterange"
          value-format="timestamp"
          @change="timeChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:sharingRecord:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['business:sharingRecord:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['business:sharingRecord:remove']"
              >删除</el-button>
            </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:sharingRecord:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sharingRecordList">
      <!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="场站" align="center" prop="stationName"/>
      <el-table-column label="代理商" align="center" prop="platformAgentName"/>
      <el-table-column label="分润规则" align="center" prop="shareRatio">
        <template slot-scope="scope">
          <el-tag
            effect="plain">
            {{ scope.row.shareRatio }}%
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="分账状态" align="center" prop="sharingStatus">
        <template slot-scope="scope">
          <el-tag :type="scope.row.sharingStatus == '1' ? '' : 'warning'" effect="plain">
            {{ scope.row.sharingStatus == '1' ? '已确认' : '分账中' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="待分账总金额分" align="center" prop="totalAmount"/>
      <el-table-column label="已分账总金额分" align="center" prop="payAmount"/>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>

      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
      &lt;!&ndash;          <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['business:sharingRecord:edit']"
                >详情
                </el-button>&ndash;&gt;
                &lt;!&ndash;          <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['business:sharingRecord:edit']"
                          >修改</el-button>
                          <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['business:sharingRecord:remove']"
                          >删除</el-button>&ndash;&gt;
              </template>
            </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改代理商分账对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1500px" append-to-body>
      <div>
        <el-select
          v-model="form.platformAgentId"
          placeholder="代理商名称"
          clearable
          @change="getAllStation"
          size="small">
          <el-option
            v-for="area in agentList"
            :key="area.id"
            :label="area.agentName"
            :value="area.id"
          />
        </el-select>
        <el-select
          style="margin:0 30px"
          v-model="form.chargeStationId"
          placeholder="场站名称"
          clearable
          :disabled="stationType"
          size="small">
          <el-option
            v-for="station in stationList"
            :key="station.id"
            :label="station.stationName"
            :value="station.id"
          />
        </el-select>
        <el-date-picker
          v-model="dateValue"
          size="small"
          type="daterange"
          :default-time="['00:00:00', '23:59:59']"
          value-format="timestamp"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
        <el-button @click="getOrderList" style="margin-left: 20px" type="primary" size="small" icon="el-icon-search"
                   circle></el-button>
      </div>
      <div style="margin-top: 20px">
        <el-table v-loading="loading" :data="orderList" empty-text="请选择分账代理商"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="订单编号" align="center" prop="id" width="90"/>
          <el-table-column label="开电方式" align="center" prop="beginChargeType">
            <template slot-scope="scope">
              <el-tag :type="scope.row.beginChargeType == '金额模式' ? '' : 'warning'" effect="plain">
                {{ scope.row.beginChargeType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="充电设备" align="center" prop="deviceName" show-overflow-tooltip/>
          <!--<el-table-column label="充电枪" align="center" prop="chargePort" width="80"/>-->
          <!--      <el-table-column label="用户ID" align="center" prop="consumerId" show-overflow-tooltip/>-->
          <el-table-column label="用户ID" align="center" prop="consumerId" width="140" show-overflow-tooltip/>
          <el-table-column label="手机号" align="center" prop="phoneNum" show-overflow-tooltip/>
          <el-table-column label="消费金额" align="center" prop="totalAmountShow" width="130"/>
          <el-table-column label="支付方式" align="center" prop="chargeTypeShow"/>
          <el-table-column label="订单状态" align="center" prop="statusType">
            <template slot-scope="scope">
              <el-tag effect="dark" type="" :color="statusTypeBg[scope.row.status]">{{ scope.row.statusType }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="耗电量(单位:度)" align="center" prop="chargeElectricity" width="120"/>

          <el-table-column label="充电开始时间" align="center" prop="createTime" width="160"/>
          <el-table-column label="充电结束时间" align="center" prop="chargeEndTime" width="160"/>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="multiple" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSharingRecord,
  getSharingRecord,
  delSharingRecord,
  addSharingRecord,
  updateSharingRecord,
  wxProfitSharing
} from "@/api/business/sharingRecord";
import {getAgentAll} from "@/api/platform/agent";
import {getAllStationByAgentId, getAllChargeStation} from "@/api/business/station"
import {getListByChargeStationId} from "@/api/business/order"

const statusTypeBg = {
  0: '#66CCCC',
  1: '#CCFF66',
  2: '#FF99CC',
  3: '#99CC33',
  4: '#FF9900',
  5: '#FFCC00',
  6: '#993366',
  7: '#FF0033'
}
export default {
  name: "SharingRecord",
  data() {
    return {
      statusTypeBg,
      dateValue: null,
      orderList: [],
      stationType: true,
      agentList: [],
      stationList: [],
      stationListAll: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代理商分账表格数据
      sharingRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chargeStationId: null,
        platformAgentId: null,
        shareInfoId: null,
        sharingStatus: null,
        totalAmount: null,
        payAmount: null,
        beginTime: null,
        endTime: null,
        timeExport: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
    this.getAgentAll()
    this.getListStation()
  },
  methods: {
    /** 查询场站列表 **/
    async getListStation() {
      let res = await getAllChargeStation()
      this.stationListAll = res.data;
      console.log(res)
    },
    timeChange(val) {
      this.queryParams.beginTime = val[0]
      this.queryParams.endTime = val[1]
    },
    async getOrderList() {
      if (!this.form.platformAgentId) {
        this.$modal.msgError("请选择代理商");
        return false
      }
      if (!this.form.chargeStationId) {
        this.$modal.msgError("请选择场站");
        return false
      }
      if (!this.dateValue) {
        this.$modal.msgError("请选择时间");
        return false
      }
      let [beginTime, endTime] = this.dateValue

      this.loading = true;
      try {
        let params = Object.assign({}, this.queryParams)
        params.pageSize = 50
        let res = await getListByChargeStationId(params, this.form.chargeStationId, beginTime, endTime)
        this.orderList = res.rows
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    async getAllStation(val) {
      let res = await getAllStationByAgentId(val)
      this.stationList = res.data
      this.stationType = false
    },
    async getAgentAll() {
      let res = await getAgentAll()
      this.agentList = res.rows
    },
    /** 查询代理商分账列表 */
    getList() {
      this.loading = true;
      listSharingRecord(this.queryParams).then(response => {
        this.sharingRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        chargeStationId: null,
        createBy: null,
        createTime: null,
        platformAgentId: null,
        shareInfoId: null,
        sharingStatus: null,
        totalAmount: null,
        payAmount: null,
        sharingVos: []
      };
      this.orderList = []
      this.dateValue = []
      this.stationType = true
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.beginTime = null
      this.queryParams.endTime = null
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.form.sharingVos = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加代理商分账";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSharingRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改代理商分账";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.loading = true
      wxProfitSharing(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.loading = false
        this.getList();
      });
      /*this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSharingRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSharingRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });*/
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除代理商分账编号为"' + ids + '"的数据项？').then(function () {
        return delSharingRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/sharingRecord/export', {
        ...this.queryParams
      }, `sharingRecord_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
